package com.yupi.project.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.mdd.mddapiclientsdk.client.MddApiClient;
import com.mdd.model.entity.InterfaceInfo;
import com.mdd.model.entity.User;
import com.yupi.project.annotation.AuthCheck;
import com.yupi.project.common.*;
import com.yupi.project.constant.CommonConstant;
import com.yupi.project.exception.BusinessException;
import com.yupi.project.exception.ThrowUtils;
import com.yupi.project.model.dto.interfaceInfo.InterfaceInfoAddRequest;
import com.yupi.project.model.dto.interfaceInfo.InterfaceInfoQueryRequest;
import com.yupi.project.model.dto.interfaceInfo.InterfaceInfoUpdateRequest;
import com.yupi.project.model.dto.interfaceInfo.InterfaceInvokeRequest;
import com.yupi.project.model.enums.InterfaceInfoStatusEnum;
import com.yupi.project.service.InterfaceInfoService;
import com.yupi.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.URL;
import java.util.List;

/**
 * 接口的接口
 *
 * @author yupi
 */
@RestController
@RequestMapping("/interfaceInfo")
@Slf4j
public class InterfaceInfoController {

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private UserService userService;

    @Resource
    private MddApiClient mddApiClient;

    // region 增删改查

    /**
     * 接口创建
     *
     * @param interfaceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addInterfaceInfo(@RequestBody InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        //先判断请求数据对象是否为空
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //对象拷贝
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);

        // 数据参数校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, true);

        User loginUser = userService.getLoginUser(request);
        interfaceInfo.setUserId(loginUser.getId());
        //接口测试
        String method = interfaceInfo.getMethod();
        String urlStr = interfaceInfo.getUrl();
        String userParams = "";
        URL url = null;
        try {
            url = new URL(urlStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String path = url.getPath();
        String host = url.getHost();
        if ("POST".equals(method)) {
            userParams = "{}";
        }
        String res;
        try {
            res = mddApiClient.invokeInterface(userParams, path, method);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "接口测试失败，请确保接口信息正确！");
        }
        //添加接口
        interfaceInfo.setPath(path);
        interfaceInfo.setHost(host);
        boolean result = interfaceInfoService.save(interfaceInfo);
        //判断是否添加成功
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        long newInterfaceInfoId = interfaceInfo.getId();
        //响应
        return ResultUtils.success(newInterfaceInfoId);
    }

    /**
     * 接口删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        //校验
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //获取用户态
        User user = userService.getLoginUser(request);

        long id = deleteRequest.getId();
        // 数据库查询接口是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 鉴权：仅本人或管理员可删除
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //删除接口
        boolean b = interfaceInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 接口更新
     *
     * @param interfaceInfoUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody InterfaceInfoUpdateRequest interfaceInfoUpdateRequest,
                                            HttpServletRequest request) {
        //判断请求数据是否为空
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //数据拷贝
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);
        // 参数校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, false);

        //获取当前用户态
        User user = userService.getLoginUser(request);
        long id = interfaceInfoUpdateRequest.getId();

        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        // 鉴权：仅本人或管理员可修改
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //修改
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取接口
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<InterfaceInfo> getInterfaceInfoById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        return ResultUtils.success(interfaceInfo);
    }

    /**
     * 获取接口列表（仅管理员可使用）
     *
     * @param interfaceInfoQueryRequest
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @GetMapping("/list")
    public BaseResponse<List<InterfaceInfo>> listInterfaceInfo(InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        if (interfaceInfoQueryRequest != null) {
            BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfo);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfo);
        List<InterfaceInfo> interfaceInfoList = interfaceInfoService.list(queryWrapper);
        return ResultUtils.success(interfaceInfoList);
    }

    /**
     * 分页获取接口列表
     *
     * @param interfaceInfoQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<InterfaceInfo>> listInterfaceInfoByPage(InterfaceInfoQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        //请求数据是否为空
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //数据拷贝
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        //获取当前页
        long current = interfaceInfoQueryRequest.getCurrent();
        //获取每页记录数
        long size = interfaceInfoQueryRequest.getPageSize();
        //排序字段
        String sortField = interfaceInfoQueryRequest.getSortField();
        //排序顺序
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();
        //获取接口的描述
        String description = interfaceInfoQuery.getDescription();
        // description 需支持模糊搜索
        interfaceInfoQuery.setDescription(null);
        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //按条件分页查询
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        Page<InterfaceInfo> interfaceInfoPage = interfaceInfoService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(interfaceInfoPage);
    }

    // endregion

    /**
     * 发布接口(管理员)
     *
     * @param idRequest
     * @param request
     * @return
     */
    @PostMapping("/online")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> onlineInterface(@RequestBody IdRequest idRequest,
                                                     HttpServletRequest request) {
        //参数校验
        if (idRequest == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //校验接口是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(idRequest.getId());
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //校验接口是否可用
        String path = oldInterfaceInfo.getPath();
        String method = oldInterfaceInfo.getMethod();
        String userNameByPost = mddApiClient.invokeInterface("",path,method);
        if (StringUtils.isBlank(userNameByPost)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"接口验证失败");
        }
        //发布接口(修改接口状态为1)
        InterfaceInfo interfaceInfo1 = new InterfaceInfo();
        interfaceInfo1.setId(idRequest.getId());
        interfaceInfo1.setStatus(InterfaceInfoStatusEnum.ONLINE.getValue());
        boolean res = interfaceInfoService.updateById(interfaceInfo1);
        ThrowUtils.throwIf(!res,ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 下线接口(管理员)
     * @param idRequest
     * @param request
     * @return
     */
    @PostMapping("/offline")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> offlineInterface(@RequestBody IdRequest idRequest,
                                                     HttpServletRequest request) {

        //参数校验
        if (idRequest == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //校验接口是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(idRequest.getId());
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //发布接口(修改接口状态为1)
        InterfaceInfo interfaceInfo1 = new InterfaceInfo();
        interfaceInfo1.setId(idRequest.getId());
        interfaceInfo1.setStatus(InterfaceInfoStatusEnum.OFFLINE.getValue());
        boolean res = interfaceInfoService.updateById(interfaceInfo1);
        ThrowUtils.throwIf(!res,ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 接口在线调用
     * @param interfaceInvokeRequest
     * @param request
     * @return
     */
    @PostMapping("/invoke")
    public BaseResponse<Object> invokeInterface(@RequestBody InterfaceInvokeRequest interfaceInvokeRequest,
                                                  HttpServletRequest request) {
        //参数校验
        if (interfaceInvokeRequest == null || interfaceInvokeRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userRequestParams = interfaceInvokeRequest.getUserRequestParams();
        ThrowUtils.throwIf(userRequestParams==null,ErrorCode.NOT_FOUND_ERROR,"请求参数不存在");
        //去除转移字符
        userRequestParams = userRequestParams.replaceAll("\n", "");
        //校验接口是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(interfaceInvokeRequest.getId());
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //判断接口是否上线
        ThrowUtils.throwIf(oldInterfaceInfo.getStatus()!=1,new BusinessException(ErrorCode.FORBIDDEN_ERROR,"接口未上线"));
        //获取当前用户
        User loginUser = userService.getLoginUser(request);
        //获取用户ak Sk
        String accessKey = loginUser.getAccessKey();
        String secretKey = loginUser.getSecretKey();
        //获得测试客户端
        MddApiClient tempClient = new MddApiClient(accessKey, secretKey);
        //获取接口信息
        String method = oldInterfaceInfo.getMethod();
        String path = oldInterfaceInfo.getPath();
        // 远程调用
        String res = null;
        try {
            res = tempClient.invokeInterface(userRequestParams, path, method);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"调用失败");
        }
        //调用APi
        return ResultUtils.success(res);
    }


}

